<template>
	<view>
		<!-- <baidu-map class="bm-view" :center="{lng: 116.404, lat: 39.915}" :zoom="1">
			<div v-for="marker of markers">
				<bm-marker :position="{lng: marker.lng, lat: marker.lat}" :title="marker.name"
					@click="infoWindowOpen(marker)">
					<bm-info-window title="车辆信息" :position="{lng: marker.lng, lat: marker.lat}" :show="marker.showFlag"
						@close="infoWindowClose(marker)" @open="infoWindowOpen(marker)">

					</bm-info-window>
				</bm-marker>
			</div>
		</baidu-map> -->
		<!-- <baidu-map class="bm-view" :center="center" :zoom="zoom" @ready="handler">
			<bm-marker class="bmMarker" :position="startPoint"
				:icon="{url: mapIcon1, size: {width: 19, height: 25}}"></bm-marker>
			<bm-marker class="bmMarker" :position="endPoint" :icon="{url: mapIcon2, size: {width: 19, height: 25}}">
			</bm-marker>
		</baidu-map> -->
		<baidu-map :style="'width:100%; height:480rpx'" :center="center" 
			></baidu-map>
	</view>
</template>

<script>
	import vConsole from "../../static/js/vconsole.min"
	export default {
		data() {
			return {
				vConsole: new vConsole(),
				// 中心位置和缩放级别
				center: {
					longitude: 116.404,
					latitude: 39.915
				},
				zoom: 3,
				// 起点和终点经纬度
				startPoint: {
					lng: 116.41287272931316,
					lat: 39.90484678673147
				},
				endPoint: {
					lng: 114.99356183689069,
					lat: 30.68072372980335
				},
				// 图标
				mapIcon1: '../../static/images/localtion.png',
				mapIcon2: '../../static/images/localtion.png',
				markers: [ // 标记点，包括起点和终点 
					{
						longitude: 116.41287272931316,
						latitude: 39.90484678673147,
						iconPath: '../../static/images/localtion.png',
						width: 30,
						height: 30
					},
					{
						longitude: 114.99356183689069,
						latitude: 30.68072372980335,
						iconPath: '../../static/images/localtion.png',
						width: 30,
						height: 30
					}
				]

			}
		},
		// mounted() {
		// 	this.handler()
		// },
		methods: {
			onMapLoaded() {
				// 在地图加载完成后，调用百度地图API进行路径规划 
				const driving = new BMap.DrivingRoute(this.$refs.map.map, {
					renderOptions: {
						map: this.$refs.map.map,
						autoViewport: true
					}
				});
				driving.search(new BMap.Point(116.404, 39.915), new BMap.Point(116.418, 39.915));

			},
			handler(bmap) {
				const driving = new BMap.DrivingRoute({
					renderOptions: {
						map: bmap,
						autoViewport: true
					},
				});
				const start = new BMap.Point(this.startPoint.lng, this.startPoint.lat);
				const end = new BMap.Point(this.endPoint.lng, this.endPoint.lat);

				driving.search(start, end);
			},
			makeCall() {
				uni.showActionSheet({
					itemList: this.itemList, //itemList字段不变
					success: function(res) {
						if (!res.cancel && res.tapIndex !== undefined) {
							uni.makePhoneCall({
								phoneNumber: this.itemList[res.tapIndex],
								success: function() {
									console.log('拨打电话成功');
								},
								fail: function() {
									console.log('拨打电话失败');
								}
							});
						}
					}.bind(this) // 绑定this作用域
				});
			},
			havetime(unixtime) {
				var date = new Date(unixtime);
				var y = date.getFullYear();
				var m = date.getMonth() + 1;
				m = m < 10 ? ('0' + m) : m;
				var d = date.getDate();
				d = d < 10 ? ('0' + d) : d;
				var h = date.getHours();
				h = h < 10 ? ('0' + h) : h;
				var minute = date.getMinutes();
				var second = date.getSeconds();
				minute = minute < 10 ? ('0' + minute) : minute;
				second = second < 10 ? ('0' + second) : second;
				return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second; //年月日时分秒
				// return y + '-' + m + '-' + d + ' ' + h + ':' + minute;
			},
			haveMonth(unixtime) {
				var date = new Date(unixtime);
				var y = date.getFullYear();
				var m = date.getMonth() + 1;
				m = m < 10 ? ('0' + m) : m;
				var d = date.getDate();
				d = d < 10 ? ('0' + d) : d;
				var h = date.getHours();
				h = h < 10 ? ('0' + h) : h;
				var minute = date.getMinutes();
				var second = date.getSeconds();
				minute = minute < 10 ? ('0' + minute) : minute;
				second = second < 10 ? ('0' + second) : second;
				return y + '' + m
				// return y + '-' + m + '-' + d + ' ' + h + ':' + minute;
			},
			haveMonthDay(unixtime) {
				var date = new Date(unixtime);
				var y = date.getFullYear();
				var m = date.getMonth() + 1;
				m = m < 10 ? ('0' + m) : m;
				var d = date.getDate();
				d = d < 10 ? ('0' + d) : d;
				var h = date.getHours();
				h = h < 10 ? ('0' + h) : h;
				var minute = date.getMinutes();
				var second = date.getSeconds();
				minute = minute < 10 ? ('0' + minute) : minute;
				second = second < 10 ? ('0' + second) : second;

				return y + '' + m + '' + d
			},
			compressImage(url) {
				return new Promise((reslove, reject) => {
					const tempFilePath = url //url是选中图片的路径
					uni.compressImage({
						src: tempFilePath,
						quality: 50, //压缩的程度
						success: (res) => {
							reslove(res.tempFilePath) //压缩成功返回的路径
						},
						fail: (error) => {
							console.log('压缩失败', error)
						}
					})
				})
			},

			selectImg() {
				let that = this
				uni.chooseImage({
					count: 6, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: function(res) {
						console.log(JSON.stringify(res.tempFilePaths));
						console.log(res.tempFiles[0]); //此处res中有所需要的信息	；
						that.toBlobName = res.tempFiles[0]
						// that.toBlobName = that.compressImage(res.tempFiles[0])
						// 获取到的应该是  blob地址
						// var toBlob = that.h5_url_to_blob(JSON.stringify(res.tempFilePaths))
						// that.toBlobName = that.h5_url_to_blob(JSON.stringify(res.tempFilePaths))

						// that.compressImage(res.tempFiles[0])
						// that.toBlobName = that.translate(that.toBlobName,0.8)
						console.log(that.toBlobName, 'toBlobtoBlobtoBlobtoBlob')
						that.before()
					},
					fail: (chooseImageError) => {
						// 选择图片失败处理
						console.error('chooseImage fail:', chooseImageError);
					}
				});
			},
			translate(imgSrc, scale) {
				//imgSrc:图片的路径
				//scale:缩放比例 0-1之间
				return new Promise((reslove, reject) => {
					var img = new Image(); //创建Image对象生成一个<img>标签
					img.src = imgSrc; //将图片路径赋给<img>标签的src
					img.onload = () => { //onload在图片加载成功后触发，在onload中完成压缩功能
						var h = img.height / 2; // 获取原本图片的宽高
						var w = img.width / 2; //默认按比例压缩,根据需求修改
						var canvas = document.createElement('canvas'); //创建画布
						var ctx = canvas.getContext('2d'); //设置为2d效果
						var width = document.createAttribute("width"); //创建属性节点
						width.nodeValue = w; //设置属性值
						var height = document.createAttribute("height");
						height.nodeValue = h;
						canvas.setAttributeNode(width); //设置画布宽高
						canvas.setAttributeNode(height);
						ctx.drawImage(img, 0, 0, w, h); //将图片贴到画布上
						//img:图片 0,0:粘贴的位置 w,h:粘贴图片的大小
						var base64 = canvas.toDataURL('image/png', scale);
						//'image/png':压缩返回图片的类型 scale:图片质量
						//如果要base64的流，可以直接将结果返回了
						canvas = null; //清除画布
						var blob = this.base64ToBlob(base64); //需要二进制流调用该方法拿到
						let blobUrl = window.URL.createObjectURL(blob); //blob地址
						reslove(blobUrl)
					}
				})
			},
			// base64转Blob
			base64ToBlob(base64) {
				var arr = base64.split(','),
					mime = arr[0].match(/:(.*?);/)[1],
					bstr = atob(arr[1]),
					n = bstr.length,
					u8arr = new Uint8Array(n);
				while (n--) {
					u8arr[n] = bstr.charCodeAt(n);
				}
				return new Blob([u8arr], {
					type: mime,
				});
			},
			before() {
				const OSS = require('ali-oss');
				let that = this
				var timestamp = new Date().getTime()
				var time = this.havetime(timestamp)
				var timeMonth = this.haveMonth(timestamp)
				var haveMonthDay = this.haveMonthDay(timestamp)
				uni.request({
					url: 'http://sts.ck9696.com/oss/ckOSSServer/getCkOSSToken',
					method: 'post',
					data: {
						'exchangeTime': time,
						'channelId': '1',
						'channelNo': '1',
						'channelPassword': '1',
						'appVersion': '1',
						'appMobileModel': '1'
					},

					success: function(res) {

						res.data.data.bucket = 'oss-token-test'
						// res.data.data.endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
						res.data.data.endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
						res.data.data.AccessKeyId = res.data.data.accessKeyId
						res.data.data.AccessKeySecret = res.data.data.accessKeySecret
						res.data.data.stsToken = res.data.data.securityToken
						console.log(res.data.data, 'res.data.datares.data.data')
						let client = new OSS(res.data.data)

						// 			console.log(client,'clientclientclientclientclientclient')
						let storeAs = null
						storeAs = '/bsh/' + timeMonth +
							'/' + haveMonthDay + Math.ceil(Math.random() * 10000000000) + '.' + 'png'
						console.log(storeAs, 'storeAsstoreAsstoreAsstoreAsstoreAsstoreAsstoreAsstoreAs')
						// let result = client.put(storeAs, that.toBlobName);

						client.put(storeAs, that.toBlobName).then(ress => {

							console.log(ress, '222222222222222222'); //此处就已经上传成功了
						}).catch(err => {
							console.log(err, '11111111111111111111111');
							console.log(JSON.parse(err), '11111111111111111111111');
						})
					},
					fail: function(err) {
						console.log(err, 'resssssssssssssssssssssssssssssssssss')
						console.log(JSON.parse(err), 'resssssssssssssssssssssssssssssssssss')
						uni.showToast({
							title: res,
							icon: 'none',
							duration: 2000
						})
					}
				})
			},
		}
	}
</script>

<style>
	.bm-view {
		width: 100%;
		height: 480rpx;
	}
</style>